package com.xie.leetcode.array;

//16. 最接近的三数之和
//        给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数，使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
//
//
//
//        示例：
//
//        输入：nums = [-1,2,1,-4], target = 1
//        输出：2
//        解释：与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
//
//
//        提示：
//
//        3 <= nums.length <= 10^3
//        -10^3 <= nums[i] <= 10^3
//        -10^4 <= target <= 10^4

import java.util.Arrays;

/**
 * @author xiezhendong
 * @date 2021/11/1
 */
public class ThreeSumClosest {

    public static void main(String[] args) {
        ThreeSumClosest threeSumClosest = new ThreeSumClosest();
        System.out.println(threeSumClosest.threeSumClosest(new int[]{-1, 2, 1, -4}, 2));
        System.out.println(threeSumClosest.threeSumClosest(new int[]{1, 1, 1, 1}, 0));
    }

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        int targetNum = 0;
        int targetValueNum = 0;
        for (int i = 0; i < nums.length; i++) {
            int lIndex = i + 1;
            int rIndex = len - 1;
            while (lIndex < rIndex) {
                int sum = nums[i] + nums[lIndex] + nums[rIndex];
                if (sum == target) {
                    return sum;
                } else if (sum < target) {
                    int targetValueNumNew = target - sum;
                    if (targetValueNum == 0) {
                        targetValueNum = targetValueNumNew;
                        targetNum = sum;
                    } else {
                        if (targetValueNumNew < targetValueNum) {
                            targetValueNum = targetValueNumNew;
                            targetNum = sum;
                        }
                    }
                    lIndex++;
                } else {
                    int targetValueNumNew = sum - target;
                    if (targetValueNum == 0) {
                        targetValueNum = targetValueNumNew;
                        targetNum = sum;
                    } else {
                        if (targetValueNumNew < targetValueNum) {
                            targetValueNum = targetValueNumNew;
                            targetNum = sum;
                        }
                    }
                    rIndex--;
                }
            }
        }

        return targetNum;
    }
}
